package com.whfc.common.util;


import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Hashtable;

/**
 * 二维码生成工具类
 *
 * @author sun_guodong
 * @description
 * @date 2020-05-14
 */
public class QRCodeUtil {

    private static Logger logger = LoggerFactory.getLogger(QRCodeUtil.class);

    private static final String CHARSET = "utf-8";

    private static final String FORMAT_NAME = "JPG";

    // 二维码尺寸
    private static final int QRCODE_SIZE = 300;

    // LOGO宽度
    private static final int WIDTH = 40;

    // LOGO高度
    private static final int HEIGHT = 40;

    // 字体大小
    private static final int FONT_SIZE = 18;


    /**
     * 生成二维码
     *
     * @param content     二维码内容
     * @param bottomDes   二维码底部描述
     * @param inputStream log图片流
     * @param destPath    生成二维码位置
     * @throws Exception
     */
    public static void encode(String content, String bottomDes, InputStream inputStream, String destPath) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, bottomDes, inputStream);
        mkdirs(destPath);
        ImageIO.write(image, FORMAT_NAME, new File(destPath));
    }

    /**
     * 解析二维码
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static String decode(File file) throws Exception {
        BufferedImage image;
        image = ImageIO.read(file);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable hints = new Hashtable();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }

    /**
     * 生成二维码图片
     *
     * @param content
     * @param bottomDes
     * @param inputStream
     * @return
     * @throws Exception
     */
    private static BufferedImage createImage(String content, String bottomDes, InputStream inputStream) throws Exception {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        int tempHeight = height;
        boolean needDescription = (null != bottomDes && !"".equals(bottomDes));
        if (needDescription) {
            tempHeight += 30;
        }
        BufferedImage image = new BufferedImage(width, tempHeight, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        // 插入图片
        if (inputStream != null) {
            QRCodeUtil.insertImage(image, inputStream);
        }
        //添加底部文字
        if (needDescription) {
            QRCodeUtil.addFontImage(image, bottomDes);
        }
        return image;
    }

    /**
     * 添加 底部图片文字
     *
     * @param source      图片源
     * @param declareText 文字本文
     */
    private static void addFontImage(BufferedImage source, String declareText) {
        BufferedImage textImage = strToImage(declareText, QRCODE_SIZE, 50);
        Graphics2D graph = source.createGraphics();
        //开启文字抗锯齿
        graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        int width = textImage.getWidth(null);
        int height = textImage.getHeight(null);

        Image src = textImage;
        graph.drawImage(src, 0, QRCODE_SIZE - 20, width, height, null);
        graph.dispose();
    }

    /**
     * 文字转图片
     *
     * @param str
     * @param width
     * @param height
     * @return
     */
    private static BufferedImage strToImage(String str, int width, int height) {
        BufferedImage textImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D) textImage.getGraphics();
        //开启文字抗锯齿
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2.setBackground(Color.WHITE);
        g2.setColor(Color.black);
        g2.clearRect(0, 0, width, height);
        g2.setPaint(Color.BLACK);
        FontRenderContext context = g2.getFontRenderContext();
        Font font = new Font("宋体", Font.BOLD, FONT_SIZE);
        g2.setFont(font);
        LineMetrics lineMetrics = font.getLineMetrics(str, context);
        FontMetrics fontMetrics = g2.getFontMetrics(font);
        float offset = (width - fontMetrics.stringWidth(str)) / 2;
        float y = (height + lineMetrics.getAscent() - lineMetrics.getDescent() - lineMetrics.getLeading()) / 2;
        g2.drawString(str, (int) offset, (int) y);

        return textImage;
    }

    /**
     * 插入图片
     *
     * @param source
     * @param inputStream
     * @throws Exception
     */
    private static void insertImage(BufferedImage source, InputStream inputStream) throws Exception {
        Image src = ImageIO.read(inputStream);
        if (src == null) {
            return;
        }
        Image image = src.getScaledInstance(WIDTH, HEIGHT, Image.SCALE_SMOOTH);
        BufferedImage tag = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        g.drawImage(image, 0, 0, null); // 绘制缩小后的图
        g.dispose();
        src = image;
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - WIDTH) / 2;
        int y = (QRCODE_SIZE - HEIGHT) / 2;
        graph.drawImage(src, x, y, WIDTH, HEIGHT, null);
        Shape shape = new RoundRectangle2D.Float(x, y, WIDTH, HEIGHT, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    /**
     * 创建文件或目录
     *
     * @param destPath
     */
    private static void mkdirs(String destPath) {
        File file = new File(destPath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

    public static void main(String[] args) throws Exception {
        File tempFile = File.createTempFile("001shebei1", ".jpg");
        String absolutePath = tempFile.getAbsolutePath();
        System.out.println(absolutePath);
        InputStream r = new FileInputStream("D:/A/ags-zhgd/whfc-mach/whfc-mach-service-api-impl/src/main/resources/200.png");
        encode("https://test.whfciot.com/ms/pages/mach.html?machId=201", "设备001的信息", r, absolutePath);

    }
}


